package com.example.mylogin.controller;

import com.example.mylogin.entity.SpatialArea;
import com.example.mylogin.pojo.dto.AreaCreateDTO;
import com.example.mylogin.pojo.dto.AreaQueryDTO;
import com.example.mylogin.service.SpatialAreaService;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.Point;
import org.locationtech.jts.geom.Polygon;
import org.locationtech.jts.io.ParseException;
import org.locationtech.jts.io.WKTReader;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/areas")
public class AreaController {
    private final SpatialAreaService areaService;
    private final WKTReader wktReader = new WKTReader();

    public AreaController(SpatialAreaService areaService) {
        this.areaService = areaService;
    }

    @PostMapping
    public SpatialArea createArea(@RequestBody AreaCreateDTO dto) throws ParseException {
        return areaService.createArea(dto);
    }

    @GetMapping("/containing")
    public List<SpatialArea> findAreasContainingPoint(
            @RequestParam String wktPoint,
            @RequestParam(required = false) Double distance) throws ParseException {

        Geometry geometry = wktReader.read(wktPoint);
        if (!(geometry instanceof Point)) {
            throw new IllegalArgumentException("Only POINT geometry is supported for this query");
        }

        AreaQueryDTO query = new AreaQueryDTO();
        query.setPoint((Point) geometry);
        if (distance != null) {
            query.setDistance(distance);
            return areaService.findAreasWithinDistance(query);
        }
        return areaService.findAreasContainingPoint(query);
    }

    @GetMapping("/{id}/area")
    public Double calculateArea(@PathVariable Long id) {
        return areaService.calculateArea(id);
    }
}
